package org.sdfc.query

import com.documentum.fc.client.IDfSession

import org.sdfc.model.dfc.collection.CollectionRow

/** View of a TypedQuery as a sequence of one or zero CollectionRow,
 *  ignoring the additional rows if any.
 */
class PreparedFirstRow (
  /** TypedQuery to be executed. */
  val query : TypedQuery,
  /** DFC session. */
  val session : IDfSession
) {
  
  /** Executes the query and applies the given function <code>rf</code>
   *  to the first row of results if there is one.
   */
  def foreach(rf : CollectionRow => Unit) {
    val coll = query.execute(session)
    try {
      coll.nextRow().foreach(rf)
    }
    finally { coll.close() }
  }
  
  /** Executes the query and collects in an Option the result of applying
   *  the given function <code>rf</code> to the first row of results.<br/>
   *  The Option is empty is there was no rows.
   */
  def map[T](rf : CollectionRow => T) : Option[T] = {
    val coll = query.execute(session)
    try {
      coll.nextRow().map(rf)
    }
    finally { coll.close() }
  }
  
}
